class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> rst;
        sort(nums.begin(), nums.end());

        for(int i = 0; i < nums.size() - 2; ++i){
            if(i != 0 && nums[i] == nums[i - 1]){
                continue;
            }

            int left = i + 1;
            int right = nums.size() - 1;

            while(left < right){
                int num = nums[i] + nums[left] + nums[right];
                if (num == 0) {
                    rst.push_back({nums[left], nums[i], nums[right]});
                }

                if(num < 0){
                    do{
                        ++left;
                    } while(left < right && nums[left] == nums[left - 1]);
                } else {
                    do{
                        right--;
                    } while(left < right && nums[right] == nums[right + 1]);
                }
            }
        }

        return rst;
    }
};